package com.hps.demo.serialization;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author heps
 * @since 2020/7/10 10:14
 */
public class JdkSerializer {

  public <T> byte[] serialize(T object) {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(bos)) {
      oos.writeObject(object);
      return bos.toByteArray();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return new byte[0];
  }

  @SuppressWarnings("unchecked")
  public <T> T deserialize(byte[] byteArr) {
    try (ByteArrayInputStream bis = new ByteArrayInputStream(byteArr);
        ObjectInputStream ois = new ObjectInputStream(bis)) {
      return (T)ois.readObject();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}
